﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace Ys.Base.Common
{
    /// <summary>
    ///  静态httpcontext
    /// </summary>
    public static class MyCoreHttpContext
    {
        private static IHttpContextAccessor _contextAccessor;
        public static HttpContext Current => _contextAccessor.HttpContext;


        internal static void Configure(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
    }

    /// <summary>
    /// 静态httpcontext
    /// </summary>
    public static class MyCoreStaticHttpContextExtensions
    {
        /// <summary>
        /// 注入静态httpContext
        /// </summary>
        /// <param name="services"></param>
        public static void AddMyCoreHttpContextAccessor(this IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }
        /// <summary>
        /// 启用静态httpcontext服务 使用方法  Seartup configure 中 app.UseStaticMyHttpContext
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseStaticMyHttpContext(this IApplicationBuilder app)
        {
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            MyCoreHttpContext.Configure(httpContextAccessor);
            return app;
        }
    }
}
